package com.booza.dao;

import java.util.Collection;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.booza.model.GameType;

/**
 * A hibernate DAO class which supports simple CRUD operations on the gametype table. 
 * No business logic here. Just the interaction with database.
 * 
 * @see GameDAO
 */
@Transactional
public class GameDAOImpl implements GameDAO
{
	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Creates new game type.
	 * 
	 * @param game
	 *          - row to be inserted
	 */
	public void createGameType(GameType game)
	{
		sessionFactory.getCurrentSession().save(game);
	}

	/**
	 * Finds list of all games in games table.
	 * 
	 * @return Return a list of the games.
	 */
	public GameType fetchGameById(Integer id)
	{
		return (GameType) sessionFactory.getCurrentSession().createCriteria(GameType.class).add(
				Restrictions.eq("gametypeid", id)).uniqueResult();
	}

	/**
	 * Find game by game name.
	 * 
	 * @param name
	 *          - game name to search for
	 * @return Returns the matching game details.
	 */
	public GameType fetchGameByName(String name)
	{
		return (GameType) sessionFactory.getCurrentSession().createCriteria(GameType.class).add(
				Restrictions.eq("name", name)).uniqueResult();
	}

	/**
	 * Find game by game ID.
	 * 
	 * @param id
	 *          -game id to search for
	 * @return Returns the matching game details.
	 */
	@SuppressWarnings("unchecked")
	public Collection<GameType> fetchGames()
	{
		return (Collection<GameType>) sessionFactory.getCurrentSession().createCriteria(GameType.class).list();
	}

	/**
	 * Updates the game details.
	 * 
	 * @param game
	 *          -row to be updated
	 */
	public void updateGameType(GameType game)
	{
		sessionFactory.getCurrentSession().saveOrUpdate(game);
	}
}
